package org.springleaf.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.springleaf.core.json.IJsonObject;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class Obj2MapUtils {

	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 转为Map对象
	 */
	private static Map toMap(Object obj) {
		if (obj instanceof IJsonObject) {
			return (Map) ((IJsonObject) obj).toJSonObject();
		} else if(obj instanceof Map){
			return (Map) obj;
		}else {
			PropertyDescriptor[] pds = PropertyUtils
					.getPropertyDescriptors(obj);
			String[] fields = new String[pds.length];
			for (int i = 0; i < pds.length; i++) {
				fields[i] = pds[i].getName();
			}
			return toMap(obj, fields);
		}
	}

	/**
	 * 将指定的属性转为Map对象
	 * 
	 * @param obj
	 *            数据源
	 * @param fields
	 *            指定的属性
	 */
	public static Map toMap(Object obj, String[] fields) {
		Map map = new HashMap();
		if (fields != null) {
			for (String field : fields) {
				try {
					Object v = PropertyUtils.getProperty(obj, field);
					if (v instanceof IJsonObject) {
						v = ((IJsonObject) obj).toJSonObject();
					} else if (v instanceof Iterable) {
						Iterable iterable = (Iterable) v;
						Iterator iterator = iterable.iterator();
						List list = new ArrayList();
						while (iterator.hasNext()) {
							Object o = iterator.next();
							list.add(toMap(o));
						}
						v = list;
					} else if(v instanceof Date){
						v = dateFormat.format(v);
					}
					map.put(field, v);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
			}
		}
		map.remove("class");
		return map;
	}

	/**
	 * 将指定的不需要的属性之外其他属性转为Map对象
	 * 
	 * @param obj
	 *            数据源
	 * @param fields
	 *            指定的不需要的属性
	 */
	public static Map toMapExcep(Object obj, String[] fields) {

		Map fieldMap = new HashMap();

		for (String field : fields)
			fieldMap.put(field, field);

		PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(obj);
		List<String> fieldList = new ArrayList<String>();

		for (PropertyDescriptor pd : pds) {
			fieldList.add(pd.getName());
		}
		for (int i = fieldList.size() - 1; i >= 0; i--) {
			if (fieldMap.containsKey(fieldList.get(i)))
				fieldList.remove(i);
		}
		fields = new String[fieldList.size()];

		for (int i = 0; i < fields.length; i++) {
			fields[i] = fieldList.get(i);
		}

		return toMap(obj, fields);
	}
	
	public static List toMapList(Collection collection) {
		Iterator iterator = collection.iterator();
		List result = new ArrayList();
		while(iterator.hasNext()){
			Object obj = iterator.next();
			result.add(toMap(obj));
		}
		return result;
	}

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
//		User user = new User();
//		user.setId(20L);
//		user.setUserName("abc");
//		user.setPassword("123");
//		user.setTel("515616");
//		user.setTrueName("leaf");
//		Map map = Obj2MapUtils.toMapExcep(user, new String[] { "id",
//				"userName", "password" });
//		System.out.println(map);

	}
	
}
